package com.tengju.bff.interfaces.manage.common.facade;

import com.tengju.bff.interfaces.manage.common.assembler.ImageFileAssembler;
import com.tengju.bff.interfaces.manage.common.vo.UploadFileVO;
import com.tengju.bff.interfaces.shared.InterfaceCode;
import com.tengju.bff.interfaces.shared.InterfaceException;
import com.tengju.user.application.common.FileService;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileFacade {

    public final FileService fileService;

    public FileFacade(FileService fileService) {
        this.fileService = fileService;
    }

    public UploadFileVO upload(MultipartFile multipartFile, Integer limitWidth,
            Integer limitHeight, Long limitSize) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
        if (bufferedImage != null) {
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (limitHeight != null && height > limitHeight){
                throw new InterfaceException(InterfaceCode.LIMIT_HEIGHT, limitHeight);
            }
            if (limitWidth != null && width > limitWidth){
                throw new InterfaceException(InterfaceCode.LIMIT_WIDTH, limitWidth);
            }
        }
        long size = multipartFile.getSize();
        if (limitSize != null && size > limitSize){
            throw new InterfaceException(InterfaceCode.LIMIT_SIZE, limitSize);
        }
        String url = fileService.upload(multipartFile);
        return ImageFileAssembler.ModelToVO(url, multipartFile);
    }
}
